package com.lx.javasunmmrize.XMLJsonUtils.T2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.json.XML;

import java.util.List;

/**
 * @Description TODO
 * @Author lx
 * @Date 2021/3/9 10:24
 **/
public class XmlToJSON03 {


    public static String xml3Json(String xmlStr) throws DocumentException {
        Document document = DocumentHelper.parseText(xmlStr);
        Element publicEle = document.getRootElement().element("Public");
        xmlToJsonList(publicEle);
        String asXML = publicEle.asXML();
        //正常模式的xml快速转json格式
        org.json.JSONObject jsonObject = XML.toJSONObject(asXML);
       JSONObject json = (JSONObject) JSON.parse(jsonObject.toString());
        return json.get("Public").toString();
    }
    @SuppressWarnings("unchecked")
    public static void xmlToJsonList(Element publicEle) {
        List<Element> elements = publicEle.elements();
        for(Element element : elements){
            if(element.attribute("value") != null){
                //先得到该值
                String value = element.attributeValue("value");
                //再去除value属性
                element.remove(element.attribute("value"));
                //再为该节点添加值
                element.setText(value);
            }else{
                //递归
                xmlToJsonList(element);
            }
        }
    }

    public static void main(String[] args) throws DocumentException {
        String x1="<?xml version=\"1.0\" encoding=\"GB18030\"?>\n" +
                "<Message>\n" +
                "    <Public>\n" +
                "        <TxnCode value=\"CT02\"/>\n" +
                "        <aaaa>\n" +
                "            <SiteID value=\"00000001\"/>\n" +
                "            <bbbb>\n" +
                "                <TermID value=\"\"/>\n" +
                "                <ffff>\n" +
                "                    <gggg>\n" +
                "                        <hhhh>\n" +
                "                            <tttt value=\"你好\"/>\n" +
                "                        </hhhh>\n" +
                "                    </gggg>\n" +
                "                </ffff>\n" +
                "            </bbbb>\n" +
                "            <TxnBatchNo value=\"20170607152322\"/>\n" +
                "        </aaaa>\n" +
                "        <TxnSeq value=\"1\">22222</TxnSeq>\n" +
                "        <TlrNo value=\"01\">33333</TlrNo>\n" +
                "        <CardNo value=\"2017000100000003\"/>\n" +
                "        <Amt value=\"0.01\">11111</Amt>\n" +
                "        <OprType value=\"01\"/>\n" +
                "        <RelTxnSsn value=\"IPEM00000000320170607152231\"/>\n" +
                "    </Public>\n" +
                "</Message>";
        System.out.println(xml3Json(x1));
}
}
